﻿using System;
using System.Collections.Generic;

using System.Text;
using OpenTK;

using OpenTK.Graphics.OpenGL;

namespace Xeno.Core
{
    public class XenoRenderTarget
    {
        public static XenoRenderTarget Bound { get; set; }
        public XenoTexture2D Attached;
        static XenoRenderTarget()
        {
            Bound = null;
        }
        public int Buffer {get;private set;}
        public XenoRenderTarget()
        {
            int buf = 0;
            GL.GenFramebuffers(1, out buf);
            Buffer = buf;
        }
        public void Bind()
        {
            if (Bound != null)
            {
                XenoDebug.LogError("Attempt to bind more than one rendertarget at once, this is not yet supported on modern gpus.", "XenoRenderTarget.Bind()");

            }
            Bound = this;
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, Buffer);
        }
        public void Unbind()
        {
            if (Bound != this)
            {
                XenoDebug.LogError("Attempt to unbind unbound render target. This isn't support, and is quite silly. Go sit in the corner and think bout what you done. :) ", "XenoRenderTarget.Unbind");

            }
            Bound = null;
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
        }

        public void AttachTexture(XenoTexture texture)
        {
            GL.FramebufferTexture2D(FramebufferTarget.Framebuffer,FramebufferAttachment.ColorAttachment0,TextureTarget.Texture2D, texture.Texture, 0);
            CheckStatus();
            GL.Clear(ClearBufferMask.ColorBufferBit);
            Attached = texture as XenoTexture2D;
        }
        public void AttachDepth(XenoTexture texture)
        {
            GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.DepthAttachment, TextureTarget.Texture2D, texture.Texture, 0);
            CheckStatus();
            GL.Clear(ClearBufferMask.DepthBufferBit);

        }
        public void CheckStatus()
        {
            FramebufferErrorCode ec = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer);
            if (ec != FramebufferErrorCode.FramebufferComplete)
            {
                XenoDebug.LogError("FrameBuffer:  "+ec.ToString(), "XenoRenderTarget.CheckStatus");
            }
        }
    }
}
